import store from "@/store";
import Vue from "vue";
import VueRouter from "vue-router";
import routes from "./routes";

// 注册路由
Vue.use(VueRouter);

// 将原来的 push/replace 方法先保存下来
const originPush = VueRouter.prototype.push;
const originReplace = VueRouter.prototype.replace;

// 重写 push 方法
VueRouter.prototype.push = function (location, okCallback, errCallback) {
  if (!okCallback && !errCallback)
    return originPush.call(this, location).catch(() => {});
  return originPush.call(this, location, okCallback, errCallback);
};
// 重写 replace 方法
VueRouter.prototype.replace = function (location, okCallback, errCallback) {
  if (!okCallback && !errCallback)
    return originReplace.call(this, location).catch(() => {});
  return originReplace.call(this, location, okCallback, errCallback);
};

// 创建路由实例
const router = new VueRouter({
  mode: "history",
  routes,
  scrollBehavior(to, from, savedPosition) {
    if (savedPosition) {
      return savedPosition;
    } else {
      return { x: 0, y: 0 };
    }
  },
});

// 设置路由导航守卫
// 设置白名单
const whiteList = [
  "home",
  "login",
  "register",
  "search",
  "detail",
  "addCartSuccess",
  "shopCart",
];
// 定义路由全局导航守卫
router.beforeEach((to, from, next) => {
  console.log(to.name);
  console.log(store.state.user.userInfo.token);
  if (whiteList.includes(to.name) || store.state.user.userInfo.token) {
    next();
    return;
  }

  next({
    name: "login",
    query: {
      // 记录之前登录之前的页面，登录完成后，跳转回去
      redirect: to.path,
    },
  });
});

export default router;
